package com.laijiale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.laijiale.constant.ML;
import com.laijiale.dto.ArticleInsertDTO;
import com.laijiale.dto.ArticlePageDTO;
import com.laijiale.dto.ArticleUpdateDTO;
import com.laijiale.entity.Article;
import com.laijiale.entity.Article;
import com.laijiale.exception.ServiceException;
import com.laijiale.vo.ArticleSimpleListVO;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.laijiale.entity.Article;
import com.laijiale.mapper.ArticleMapper;
import com.laijiale.service.ArticleService;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.laijiale.entity.table.ArticleTableDef.ARTICLE;


/**
 * 新闻表 服务层实现。
 *
 * @author laijiale
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "article")
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>  implements ArticleService{

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(ArticleInsertDTO dto) {
        //标题查重
        if(QueryChain.of(mapper).where(ARTICLE.TITLE.eq(dto.getTitle())).exists()){
            throw new ServiceException("新闻标题已存在") ;
        }
        //组装entity实体类
        Article article= BeanUtil.copyProperties(dto,Article.class);
        article.setCreated(LocalDateTime.now());
        article.setUpdated(LocalDateTime.now());
        return mapper.insert(article)>0;

    }

    @Cacheable(key = "#p0",condition = "#p0 !=null",unless = "#result ==null")
    @Override
    public Article select(Long id) {
        return mapper.selectOneWithRelationsById(id);
    }
    @Cacheable(key = "#root.methodName",
            unless = "#result == null"
    )
    @Override
    public List<ArticleSimpleListVO> simpleList() {
        List<ArticleSimpleListVO> articleSimpleListVOS=QueryChain.of(mapper).listAs(ArticleSimpleListVO.class);
        return articleSimpleListVOS;
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition ="#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Article> page(ArticlePageDTO dto) {
        QueryChain<Article> queryChain = QueryChain.of(mapper)
                .orderBy(ARTICLE.IDX.asc(), ARTICLE.ID.desc());

        // title 条件
        String title = dto.getTitle();
        if(ObjectUtil.isNotNull(title)) {
            queryChain.where(ARTICLE.TITLE.like(title));
        }

        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }


    @CacheEvict(allEntries = true)
    @Override
    public boolean update(ArticleUpdateDTO dto) {

        // 标题查重
        if (QueryChain.of(mapper).
                where(ARTICLE.TITLE.eq(dto.getTitle()))
                .and(ARTICLE.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("新闻标题已存在");
        }

        // 组装 entity 实体类
        Article article = BeanUtil.copyProperties(dto, Article.class);
        // 设置 entity 默认值
        article.setUpdated(LocalDateTime.now());
        return UpdateChain.of(article).where(ARTICLE.ID.eq(article.getId())).update();
    }
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        return mapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        return mapper.deleteBatchByIds(ids) > 0;
    }
    @Cacheable(key = "#root.methodName",
            unless = "#result == null"
    )
    @Override
    public List<Article> top(Long N) {
        List<Article> articles= QueryChain.of(mapper).limit(N).list();
        return articles;
    }

}
